package com.meiyuetao.myt.md.service;

import java.util.List;

import lab.s2jh.core.dao.BaseDao;
import lab.s2jh.core.service.BaseService;
import lab.s2jh.core.service.Validation;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.meiyuetao.myt.md.dao.CommodityCirclePresentDao;
import com.meiyuetao.myt.md.dao.CommodityDao;
import com.meiyuetao.myt.md.entity.Commodity;
import com.meiyuetao.myt.md.entity.CommodityCirclePresent;

@Service
@Transactional
public class CommodityCirclePresentService extends BaseService<CommodityCirclePresent, Long> {

    @Autowired
    private CommodityCirclePresentDao commodityCirclePresentDao;

    @Autowired
    private CommodityDao commodityDao;

    @Override
    protected BaseDao<CommodityCirclePresent, Long> getEntityDao() {
        return commodityCirclePresentDao;
    }

    @Override
    public CommodityCirclePresent save(CommodityCirclePresent entity) {
        if (entity.getCircleMonthCount() == null) {
            Validation.isTrue(entity.getSendByCircleIndex() <= 3 && entity.getSendByCircleIndex() >= 1, "送出期数有效值1,2或3");
        } else {
            Validation.isTrue(entity.getSendByCircleIndex() <= entity.getCircleMonthCount(), "送出期数不能大于周期购期数");
        }
        Commodity commodity = commodityDao.findOne(entity.getCommodity().getId());
        commodity.setCirclePresent(true);
        commodityDao.save(commodity);
        return super.save(entity);
    }

    @Override
    public void delete(CommodityCirclePresent entity) {
        Commodity commodity = entity.getCommodity();
        super.delete(entity);
        List<CommodityCirclePresent> commodityCirclePresents = commodityCirclePresentDao.findByCommodity(commodity);
        if (CollectionUtils.isEmpty(commodityCirclePresents)) {
            commodity.setCirclePresent(false);
            commodityDao.save(commodity);
        }
    }
}
